const express = require('express');
const path = require('path');
const { sleep } = require('./utils');
const app = express();
const bodyParser = require('body-parser');
console.log('__dirname=', __dirname);
console.log('cwd=', process.env);

// However, the path that you provide to the express.
// static function is relative to the directory from where you launch your node process.
// If you run the express app from another directory,
// it’s safer to use the absolute path of the directory that you want to serve:
// const path = require('path')
// app.use('/static', express.static(path.join(__dirname, 'public')))
// 解析请求体
app.use(bodyParser.json());
// app.get('/', (req, res) => {
//   res.send('Hello World');
// });
// app.use(express.static('static'));
app.use(express.static(path.resolve(__dirname, 'static')));
/* 加路径前缀 */
// app.use('/static',express.static('static'))
app.post('/first/:id', (req, res) => {
  let { method, query, body, params, headers } = req;
  res.send({ method, query, body, params, headers });
});
// app.get('/file/:name', function (req, res, next) {
//   var options = {
//     root: path.join(__dirname, 'public'),
//     dotfiles: 'deny',
//     headers: {
//       'x-timestamp': Date.now(),
//       'x-sent': true
//     }
//   }

//   var fileName = req.params.name
//   res.sendFile(fileName, options, function (err) {
//     if (err) {
//       next(err)
//     } else {
//       console.log('Sent:', fileName)
//     }
//   })
// })
app.get('/css/sleep3000-common.css', async function (req, res, next) {
  // var options = {
  //   root: path.join(__dirname, 'public'),
  //   dotfiles: 'deny',
  //   headers: {
  //     'x-timestamp': Date.now(),
  //     'x-sent': true
  //   }
  // }

  // var fileName = req.params.name
  // res.sendFile(fileName, options, function (err) {
  //   if (err) {
  //     next(err)
  //   } else {
  //     console.log('Sent:', fileName)
  //   }
  // })
  await sleep(6000);
  const filePath = path.resolve(__dirname, 'static/css/common.css');
  res.sendFile(filePath);
  next();
});
app.get('/js/sleep3000-logDiv.js', async function (req, res, next) {
  await sleep(3000);
  const filePath = path.resolve(__dirname, 'static/js/logDiv.js');
  res.sendFile(filePath);
  next();
});
app.get('/js/sleep5000-logDiv.js', async function (req, res, next) {
  await sleep(5000);
  const filePath = path.resolve(__dirname, 'static/js/logDiv1.js');
  res.sendFile(filePath);
  next();
});
const testRouter = require('./routes/test.js');
var myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
};
// 在所有的路由生效
// app.use( myLogger)
// 在指定的路由生效
app.use('/test/*', myLogger);
app.use('/test', testRouter);
// 404中间件
app.use((req, res, next) => {
  res.status(404).send('Not Found');
  next();
});
// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  next();
  res.status(500).send('服务器出错了!');
});
app.listen(9000, () => console.log('启动成功'));
